package com.wisemoresystem.seal.util.task;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.ne.framework.data.task.Task;
import org.ne.framework.data.util.PackageTools;

import com.wisemoresystem.seal.util.SpringTools;

public class TaskTools {

	private static String servicePack = "com.wisemoresystem.seal.service";

	public static Map<String, TaskBean> tasks = new HashMap<String, TaskBean>();

	static {
		init();
	}

	// 初始化 Task
	public static void init() {

		List<Class<?>> services = PackageTools.getClasses(servicePack);
		// 遍历所有 service
		for (Class<?> service : services) {
			Method[] methods = service.getMethods();
			// 遍历所有 函数
			for (Method method : methods) {
				if (!method.isAnnotationPresent(Task.class)) {
					continue;
				}
				Task taskAnno = method.getAnnotation(Task.class);

				TaskBean tb = new TaskBean();
				tb.setCode(taskAnno.code());
				tb.setClazz(service);
				tb.setMethod(method);
				tb.setTip(taskAnno.tip());

				tasks.put(taskAnno.code(), tb);
			}

		}
	}

	// 获取某 code 的任务数
	public static long getTaskCnt(String code) {
		Long cnt = 0L;
		TaskBean tb = tasks.get(code);
		if (tb == null) {
			return cnt;
		}
		Object obj = SpringTools.getWebBean(tb.getClazz());
		Method method = tb.getMethod();
		try {
			cnt = (Long) method.invoke(obj);
		} catch (Exception e) {
			System.err.println("----------->>"+method);
			e.printStackTrace();
		}
		return cnt;
	}

	// 循环获取所有任务
	public static List<Map<String, String>> loopTask(Set<String> codes) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (String code : codes) {
			if (!tasks.containsKey(code)) {
				continue;
			}
			Long cnt = TaskTools.getTaskCnt(code);
			if (cnt == 0) {
				// 零的去到前端消除选择;
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", code);
			map.put("cnt", cnt + "");
			list.add(map);
		}
		return list;
	}

	public static void main(String[] args) {
		System.err.println(tasks);
	}

}
